    //
//  DetailViewController.swift
//  Swift-TableView-Example
//
//  Created by Bilal ARSLAN on 12/10/14.
//  Copyright (c) 2014 Bilal ARSLAN. All rights reserved.
//

import Foundation
import UIKit
import Alamofire
import SwiftyJSON
import KeychainSwift

class FriendChat: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
    
    var PlatNumberStr:String?
    var FriendIDStr:String?
    var FriendTopicStr:String?
    
    
    //从沙盒中获取数据
    let keychain = KeychainSwift(keyPrefix: "myTestKey_")
    
    @IBOutlet weak var PrivateMsg_txt: UITextField!
    
    
    //
    @IBOutlet weak var PrivateMsgList: UITableView!
    
    //数组
    var PrivateMessages = [Message]()
    var tableData:[JSON]=[]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tabBarController!.tabBar.hidden = true;
        print(PlatNumberStr)
        navigationItem.title = PlatNumberStr
    
        PrivateMsgList?.dataSource = self;
        PrivateMsgList?.delegate = self;
        
        self.PrivateMsg_txt.delegate = self
        self.PrivateMsg_txt.placeholder = "来参与互动吧"
        
        var parameters = [
            "user1":keychain.get("registerUserID")!,
            "user2":FriendIDStr!,
            "page": "1"
        ]
        let BaseUrl = "http://42.62.18.210:8090/apiradio/ar/getChats?user2="+FriendIDStr!+"&page=1"+"&user1="+keychain.get("registerUserID")!
        
        //print(FriendIDStr)
        print(BaseUrl)
        
        Alamofire.request(.GET, BaseUrl).responseJSON { response in
            if let result = response.result.value {
                print(result)
                //请求到数据
                let json = JSON(result)
                if String(json["msg"]) == "200" {
                    if let channels = json["obj"].array {
                        self.tableData = channels.reverse()
                        for var i = 0; i < self.tableData.count; i++
                        {
                            let rowData:JSON = self.tableData[i]
                            if String(rowData["sender"]) == self.keychain.get("QCDTUSERNAME") {
                                self.PrivateMessages.append(Message(PlatNumber: "我自己", PortailUrl: String(rowData["user1hp"]), MsgText: String(rowData["chat"]), TimeText: "2016-01-01"))
                            }else {
                                self.PrivateMessages.append(Message(PlatNumber: String(rowData["sender"]), PortailUrl: String(rowData["user1hp"]), MsgText: String(rowData["chat"]), TimeText: "2016-01-01"))
                            }
                            
                            
                        }
                        
                        self.PrivateMsgList!.reloadData()
                    }
                }
            }
        }
        
        //之后注册通知函数
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "privateMsgPara:", name: "privateNotification", object: nil)
    }
    

    
    @IBAction func sendPrivateMsg(sender: AnyObject) {
        //使用pub进行发送消息
        if PrivateMsg_txt.text != "" {
            print("发送")
            
            let returnValue = self.send_msg();
            if returnValue == 0 {
                //隐藏键盘和文本框下拉
                UIView.animateWithDuration(0.3) { () -> Void in
                    var frame:CGRect = self.view.frame
                    frame.origin.y = 0.0
                    self.view.frame = frame
                }                
                
                //在table中增加一条数据
                self.PrivateMessages.append(Message(PlatNumber: "我自己", PortailUrl: "user/header/tx.png", MsgText: PrivateMsg_txt.text!, TimeText: "2015-12-18"))
                
                self.PrivateMsgList.reloadData()
                
                PrivateMsg_txt.resignFirstResponder()
                PrivateMsg_txt.text = nil
                
                self.noticeSuccess("发送成功", autoClear: true, autoClearTime: 1)
                //滚动到最后一行
                self.PrivateMsgList.setContentOffset(CGPointMake(0, self.PrivateMsgList.contentSize.height-self.PrivateMsgList.bounds.size.height), animated: true)
            }
            
        }
        
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //重新恢复文本框
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        UIView.animateWithDuration(0.3) { () -> Void in
            var frame:CGRect = self.view.frame
            frame.origin.y = 0.0
            self.view.frame = frame
        }
        
        PrivateMsg_txt.resignFirstResponder()
        return true
    }
    
    //在即将输入文本时，将文本框弹出
    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        print("begin edit")
        
        var offset:CGFloat = self.view.frame.size.height - (self.PrivateMsg_txt.frame.origin.y + PrivateMsg_txt.frame.size.height + 216 + 50)
        
        if offset <= 0 {
            UIView.animateWithDuration(0.3, animations: { () -> Void in
                var frame:CGRect = self.view.frame
                frame.origin.y = offset
                self.view.frame = frame
            })
        }
        
        return true
    }
    
    //privateChatCell
    // MARK: - UITableView DataSource Methods
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let identifier: String = "privateChatCell"
        
        var cell: PrivateChatList! = tableView.dequeueReusableCellWithIdentifier(identifier) as? PrivateChatList
        cell.selectionStyle = UITableViewCellSelectionStyle.None
        if cell == nil {
            cell = PrivateChatList(style: UITableViewCellStyle.Value1, reuseIdentifier: identifier)
        }
        
        cell.configurateTheCell(PrivateMessages[indexPath.row])
        //configurateTheCell();
        
        return cell!
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return PrivateMessages.count
    }
    
    override func viewWillDisappear(animated: Bool) {
        self.tabBarController!.tabBar.hidden = false;
    }
    
    
    //函数
    func privateMsgPara(notification:NSNotification)
    {
        //=============
        let userInfo = notification.userInfo as! [String: AnyObject]
        let value1 = userInfo["value1"] as! String
        let value2 = userInfo["value2"] as! String
        let value3 = userInfo["value3"] as! String
        
        print(value1)
        print(value2)
        print(value3)
        
        //首先判断是不是和当前好友匹配
        if value2 == FriendIDStr {
            //相同的话可以展示了
            let now = NSDate()
            var dateFormatter2 = NSDateFormatter()
            dateFormatter2.dateFormat = "yyyy-MM-dd HH:mm"
            
            let nowString = dateFormatter2.stringFromDate(now)
            self.PrivateMessages.append(Message(PlatNumber: self.PlatNumberStr!, PortailUrl: "user/header/tx.png", MsgText: value3, TimeText: nowString))
            
            dispatch_async(dispatch_get_main_queue(),{
                self.PrivateMsgList!.reloadData()
                
                //滚动到最后一行
                self.PrivateMsgList.setContentOffset(CGPointMake(0, self.PrivateMsgList.contentSize.height-self.PrivateMsgList.bounds.size.height), animated: true)
            })
            
        }
        
        /*
        var str = title.object as! String
        print("WOCAOCAO")
        print(str)
        
        self.PrivateMessages.append(Message(PlatNumber: self.PlatNumberStr!, PortailUrl: "user/header/tx.png", MsgText: str, TimeText: "2016-01-01"))
        
        dispatch_async(dispatch_get_main_queue(),{
            self.PrivateMsgList!.reloadData()
            
            //滚动到最后一行
            self.PrivateMsgList.setContentOffset(CGPointMake(0, self.PrivateMsgList.contentSize.height-self.PrivateMsgList.bounds.size.height), animated: true)
        })*/
        
        //self.msgList?.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
    }
    
    /*
    func privateMsgPara(title:NSNotification)
    {
        var str = title.object as! String
        print("WOCAOCAO！！！！")
        print(str)
        
        PrivateMessages.append(Message(PlatNumber: "匿名", PortailUrl: "频道播放图片", MsgText: "kuaixiang", TimeText: "2015-0101"))
        
        self.PrivateMsgList!.reloadData()
        //PrivateMsgList.reloadData()
        
        //self.PrivateMsgList.reloadData()
        
        
        //self.PrivateMessages.append(Message(PlatNumber: String(rowData["sender"]), PortailUrl: String(rowData["user1hp"]), MsgText: String(rowData["chat"]), TimeText: "20160101"))
        //dispatch_async(dispatch_get_main_queue(),{
        //  self.PrivateListTable.reloadData()
        //self.PrivateListTable?.reloadData()
        //})
        
        
        //self.msgList?.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
        
    }*/
    
    
    //发送消息(目前只支持消息)
    func send_msg()->Int32 {
        //在这里就可以写pub函数
        //test1--发送消息
        var pub_object = carRadio_pub()
        
        let PlatNum = keychain.get("QCDTUSERNAME")
        
        let channelIDInt = "123"
        var userUUID:String?
        if keychain.get("registerUserID") != nil {
            userUUID =  keychain.get("registerUserID")
            pub_object.user_type = 1; //已登录状态
        }else {
            userUUID =  keychain.get("QCDTSEVERUUID")
            pub_object.user_type = 0; //未登录状态
        }
        
        

        
        let unsafePointerOfN1 = (userUUID! as NSString).UTF8String
        pub_object.uuid = UnsafeMutablePointer(unsafePointerOfN1)
        
        let unsafePointerOfN2 = (channelIDInt as NSString).UTF8String
        pub_object.channel_id = UnsafeMutablePointer(unsafePointerOfN2)
        
        pub_object.client_type = 1;
        pub_object.quiet = false;
        pub_object.retain = false;
        
        let unsafePointerOfN3 = ("/home" as NSString).UTF8String
        pub_object.portrait_path = UnsafeMutablePointer(unsafePointerOfN3)
        
        let unsafePointerOfN4 = ("/storage/emulated/0/1.txt" as NSString).UTF8String
        pub_object.file_path = UnsafeMutablePointer(unsafePointerOfN4)
        
        let unsafePointerOfN5 = (PrivateMsg_txt.text! as NSString).UTF8String
        pub_object.message = UnsafeMutablePointer(unsafePointerOfN5)
        
        let unsafePointerOfN6 = (FriendTopicStr! as NSString).UTF8String
        pub_object.topic = UnsafeMutablePointer(unsafePointerOfN6)
        
        let unsafePointerOfN7 = ("123.56.93.31" as NSString).UTF8String
        pub_object.server_ip = UnsafeMutablePointer(unsafePointerOfN7)
        
        pub_object.server_port = 1883;                  // 服务器端口号
        
        pub_object.sender_type = 1;            //资源类型: 1-Java调用C; 2-用户发送; 3-运营发送; 4-机器人发送
        pub_object.trans_mode = 2;          // 传输信息类型: 1.语音 2.消息 3.点赞命令 4.上线命令 5.下线命令
        pub_object.file_type = 1;        // 文件类型:音频(mp3、amr等等)
        pub_object.audio_play_time = 3;   // 语音发送时长，如果不是语音则为0
        
        pub_object.chat_mode = 3;        //私聊模式
        
        let unsafePointerOfN8 = (FriendIDStr! as NSString).UTF8String
        pub_object.toUserID = UnsafeMutablePointer(unsafePointerOfN8)
        
        pub_object.product_type = 1;         // 产品类型
        
        let unsafePointerOfN9 = ("kx" as NSString).UTF8String
        pub_object.product_id = UnsafeMutablePointer(unsafePointerOfN9)
        
        let unsafePointerOfN10 = ("苹果" as NSString).UTF8String
        pub_object.brand = UnsafeMutablePointer(unsafePointerOfN10)
        
        let unsafePointerOfN11 = ("iPhone9.1" as NSString).UTF8String
        pub_object.phone_type = UnsafeMutablePointer(unsafePointerOfN11)
        
        
        let unsafePointerOfN12 = (PlatNum! as NSString).UTF8String
        pub_object.user_name = UnsafeMutablePointer(unsafePointerOfN12)
        
        let returnValue = pub_send_msg(pub_object)
        
        print(returnValue)
        return returnValue;
    }

    
    
}